1
|
1 |
|
const db = require("../db/database.js"); |
2
|
|
|
|
3
|
1 |
|
module.exports = (function () { |
4
|
1 |
|
const dataFields = "invoiceId as id, o.orderId as order_id," + |
5
|
|
|
" customerName as name, customerAddress as address," + |
6
|
|
|
" customerZip as zip, customerCity as city," + |
7
|
|
|
" customerCountry as country, (totalPrice / 100) as total_price"; |
8
|
|
|
|
9
|
|
|
function getInvoices(res, apiKey) { |
10
|
2 |
|
db.all("SELECT " + dataFields + |
11
|
|
|
" FROM invoices i" + |
12
|
|
|
" INNER JOIN orders o ON o.orderId = i.orderId AND o.apiKey = i.apiKey" + |
13
|
|
|
" WHERE i.apiKey = ?", |
14
|
|
|
apiKey, (err, rows) => { |
15
|
2 |
|
if (err) { |
16
|
|
|
return res.status(500).json({ |
17
|
|
|
errors: { |
18
|
|
|
status: 500, |
19
|
|
|
source: "/invoices", |
20
|
|
|
title: "Database error", |
21
|
|
|
detail: err.message |
22
|
|
|
} |
23
|
|
|
}); |
24
|
|
|
} |
25
|
|
|
|
26
|
2 |
|
res.json( { data: rows } ); |
|
|
|
|
27
|
|
|
}); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
function getInvoice(res, apiKey, invoiceId) { |
31
|
3 |
|
if (Number.isInteger(parseInt(invoiceId))) { |
32
|
2 |
|
db.get("SELECT " + dataFields + |
33
|
|
|
" FROM invoices i" + |
34
|
|
|
" INNER JOIN orders o ON o.orderId = i.orderId AND o.apiKey = i.apiKey" + |
35
|
|
|
" WHERE i.apiKey = ? AND invoiceId = ?", |
36
|
|
|
apiKey, |
37
|
|
|
invoiceId, |
38
|
|
|
(err, row) => { |
39
|
2 |
|
if (err) { |
40
|
|
|
return res.status(500).json({ |
41
|
|
|
errors: { |
42
|
|
|
status: 500, |
43
|
|
|
source: "/invoice/" + invoiceId, |
44
|
|
|
title: "Database error", |
45
|
|
|
detail: err.message |
46
|
|
|
} |
47
|
|
|
}); |
48
|
|
|
} |
49
|
|
|
|
50
|
2 |
|
res.json( { data: row } ); |
|
|
|
|
51
|
|
|
}); |
52
|
|
|
} else { |
53
|
1 |
|
res.status(400).json({ |
54
|
|
|
errors: { |
55
|
|
|
status: 400, |
56
|
|
|
detail: "Required attribute invoice id " + |
57
|
|
|
" is not an integer." |
58
|
|
|
} |
59
|
|
|
}); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
function addInvoice(res, body) { |
64
|
5 |
|
db.run("INSERT INTO invoices (invoiceId, orderId, totalPrice, apiKey)" + |
65
|
|
|
" VALUES (?, ?, ?, ?)", |
66
|
|
|
body.id, |
67
|
|
|
body.order_id, |
68
|
|
|
body.total_price * 100, |
69
|
|
|
body.api_key, (err) => { |
70
|
5 |
|
if (err) { |
71
|
4 |
|
return res.status(500).json({ |
72
|
|
|
errors: { |
73
|
|
|
status: 500, |
74
|
|
|
source: "POST /invoice", |
75
|
|
|
title: "Database error", |
76
|
|
|
detail: err.message |
77
|
|
|
} |
78
|
|
|
}); |
79
|
|
|
} else { |
|
|
|
|
80
|
1 |
|
res.status(201).json({ data: body }); |
|
|
|
|
81
|
|
|
} |
82
|
|
|
}); |
83
|
|
|
} |
84
|
|
|
|
85
|
1 |
|
return { |
86
|
|
|
getInvoices: getInvoices, |
87
|
|
|
getInvoice: getInvoice, |
88
|
|
|
addInvoice: addInvoice |
89
|
|
|
}; |
90
|
|
|
}()); |
91
|
|
|
|